package org.dromara.work.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.work.domain.SgjCheck;
import org.dromara.work.domain.SgjCheckReply;
import org.dromara.work.domain.bo.SgjCheckReplySaveBo;
import org.dromara.work.domain.bo.SgjCheckSaveBo;
import org.dromara.work.domain.bo.SgjQueryBo;
import org.dromara.work.domain.vo.SgjBriefVo;
import org.dromara.work.domain.vo.SgjCheckVo;
import org.dromara.work.domain.vo.SgjGeoVo;
import org.dromara.work.mapper.SgjCheckMapper;
import org.dromara.work.mapper.SgjCheckReplyMapper;
import org.dromara.work.service.ISgjCheckService;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Collection;
import java.util.List;

/**
 * 测试单表Service业务层处理
 *
 * @author Lion Li
 * @date 2021-07-26
 */
@RequiredArgsConstructor
@Service
public class ISgjCheckServiceImpl implements ISgjCheckService {

    private final SgjCheckMapper baseMapper;

    private final SgjCheckReplyMapper replyMapper;

    @Override
    public SgjCheckVo queryById(String id) {
        SgjCheck base= baseMapper.selectOne(new LambdaQueryWrapper<SgjCheck>().eq(SgjCheck::getYwid,id));
        SgjCheckReply reply= replyMapper.selectOne(new LambdaQueryWrapper<SgjCheckReply>().eq(SgjCheckReply::getYwid,id));
        SgjGeoVo geo=baseMapper.queryGeoFile(id);
        SgjCheckVo entity=new SgjCheckVo();
        if(base!=null){
            entity.setBase(base);
        }
        if(reply!=null){
            entity.setApprove(reply);
        }
        if(geo!=null){
            entity.setGeo(geo);
        }
        return entity;
    }


    /**
     * 自定义分页查询
     */
    @Override
    public TableDataInfo<SgjBriefVo> customPageList(SgjQueryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SgjCheck> lqw = buildQueryWrapper(bo);
        Page<SgjBriefVo> result = baseMapper.selectSgjPage(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }


    private LambdaQueryWrapper<SgjCheck> buildQueryWrapper(SgjQueryBo bo) {

        LambdaQueryWrapper<SgjCheck> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getXzqh()), SgjCheck::getQumc, bo.getXzqh());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), SgjCheck::getApproval, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), SgjCheck::getRegRoadName, bo.getTitle());

        lqw.orderByDesc(SgjCheck::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insertByBo(SgjCheckSaveBo bo) {
        SgjCheck add = MapstructUtils.convert(bo, SgjCheck.class);
        validEntityBeforeSave(bo);
        add.setShape("'"+bo.getShape()+"'");
        boolean flag = baseMapper.insertGeoLineEntity(add) > 0;
        return flag;
    }

    @Override
    public Boolean insertReplyByBo(SgjCheckReplySaveBo bo) {
        SgjCheckReply add = MapstructUtils.convert(bo, SgjCheckReply.class);
        validEntityBeforeReplySave(add);
        boolean flag = replyMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        //推送数公基
        // 目标URL
        String url = "http://172.27.247.36:8075/addrSearch/source/api/road/roadNamedOut";
        // 创建JSON对象
        JSONObject jsonBody = new JSONObject();
        jsonBody.putOnce("ywid", bo.getYwid());
        jsonBody.putOnce("approval_msg", bo.getRegRoadName());
        jsonBody.putOnce("current_name",bo.getCurrentName());
        jsonBody.putOnce("road_type",bo.getRoadType());
        jsonBody.putOnce("named_describe",bo.getNamedDescribe());
        jsonBody.putOnce("named_situation",bo.getNamedSituation());
        jsonBody.putOnce("road_start",bo.getRoadStart());
        jsonBody.putOnce("road_end",bo.getRoadLength());
        jsonBody.putOnce("road_length",bo.getRoadLength());
        jsonBody.putOnce("road_width",bo.getRoadWidth());
        jsonBody.putOnce("road_move",bo.getRegRoadName());
        jsonBody.putOnce("project_id",bo.getProjectId());
        jsonBody.putOnce("project_name",bo.getProjectName());
        jsonBody.putOnce("reason",bo.getReason());
        jsonBody.putOnce("comment",bo.getComment());
        jsonBody.putOnce("approval",bo.getApproval());
        String time= Calendar.getInstance().getTimeInMillis()+"";
        String md5= SecureUtil.md5(time+"123@Abc.com");
        String json= HttpUtil.get("http://172.27.247.36:8075/addrSearch/addrMatch/auth/getToken?user=ezsmzj&secret="+md5+"&time="+time);
        JSONObject obj=JSONUtil.parseObj(json);
        String token="";
        if(obj.getJSONObject("data")!=null){
            token=obj.getJSONObject("data").getStr("token");
        }

        // 发送POST请求
        String response = HttpUtil.createPost(url)
            .header("token", token)
            .body(jsonBody.toString())
            .execute()
            .body();

        // 打印响应结果
        System.out.println(response);
        return flag;
    }

    @Override
    public Boolean updateByBo(SgjCheckSaveBo bo) {
        SgjCheck update = MapstructUtils.convert(bo, SgjCheck.class);
       // validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SgjCheckSaveBo entity) {
        //TODO 做一些数据校验,如唯一约束
        SgjCheck vo=baseMapper.selectOne(new LambdaQueryWrapper<SgjCheck>().eq(SgjCheck::getYwid,entity.getYwid()));
        if(vo!=null){

        }
    }
    private void validEntityBeforeReplySave(SgjCheckReply entity) {
        //TODO 做一些数据校验,如唯一约束

    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            List<SgjCheck> list = baseMapper.selectByIds(ids);
            if (list.size() != ids.size()) {
                throw new ServiceException("您没有删除权限!");
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean saveBatch(List<SgjCheck> list) {
        return baseMapper.insertBatch(list);
    }
}
